<template>
  <div id="course">
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 搜索区域 -->
          <el-input placeholder="请输入课程名称或ID"
            v-model="queryInfo.query"
            clearable>
            <template #append>
              <el-button @click="handleSearch">
                <el-icon>
                  <search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary"
            @click="addDialogVisible = true">添加课程</el-button>
        </el-col>
      </el-row>
      <!-- 课程列表区域 -->
      <el-table :data="courseList"
        :row-class-name="getRowClass"
        border
        stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="课程ID"
          prop="courseId"></el-table-column>
        <el-table-column label="课程名称"
          prop="courseName"
          width="150px"></el-table-column>
        <el-table-column label="课程简介"
          width="400px">
          <template #default="scope">
            <div class="course-info">{{ scope.row.courseInfo }}</div>
          </template>
        </el-table-column>
        <el-table-column label="授课教师ID"
          prop="teacherId"></el-table-column>
        <el-table-column label="操作"
          width="200px">
          <template v-slot="scope">
            <!-- 修改按钮 -->
            <el-button type="primary"
              @click="showEditDialog(scope.row.courseId)">
              <el-icon>
                <edit />
              </el-icon>
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
              @click="handleDelete(scope.row.courseId)">
              <el-icon>
                <delete />
              </el-icon>
            </el-button>
            <!-- 查看班级按钮 -->
            <el-button type="success"
              @click="viewClasssByCourse(scope.row.courseId)">
              <el-icon>
                <school />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination v-model:current-page="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>

    <!-- 添加课程对话框 -->
    <el-dialog v-model="addDialogVisible"
      title="添加课程"
      width="50%">
      <el-form :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="120px"> <!-- 增加标签宽度 -->
        <el-form-item label="课程ID"
          prop="courseId">
          <el-input v-model="addForm.courseId"
            autocomplete="off" />
        </el-form-item>
        <el-form-item label="课程名称"
          prop="courseName">
          <el-input v-model="addForm.courseName"
            autocomplete="off" />
        </el-form-item>
        <el-form-item label="课程简介"
          prop="courseInfo">
          <el-input type="textarea"
            v-model="addForm.courseInfo"
            :rows="4"
            autocomplete="off" />
        </el-form-item>
        <el-form-item label="授课教师ID"
          prop="teacherId">
          <el-input v-model="addForm.teacherId"
            autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary"
          @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改课程对话框 -->
    <el-dialog v-model="editDialogVisible"
      title="修改课程信息"
      width="50%">
      <el-form :model="editForm"
        ref="editFormRef"
        label-width="120px"> <!-- 增加标签宽度 -->
        <el-form-item label="课程ID">
          <el-input v-model="editForm.courseId"
            disabled /> <!-- 不可修改 -->
        </el-form-item>
        <el-form-item label="课程名称"
          prop="courseName">
          <el-input v-model="editForm.courseName" />
        </el-form-item>
        <el-form-item label="课程简介"
          prop="courseInfo">
          <el-input type="textarea"
            v-model="editForm.courseInfo"
            :rows="4" />
        </el-form-item>
        <el-form-item label="授课教师ID"
          prop="teacherId">
          <el-input v-model="editForm.teacherId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary"
          @click="submitEditForm">保存修改</el-button>
      </template>
    </el-dialog>

    <!-- 查看课程班级对话框 -->
    <el-dialog v-model="viewClasssDialogVisible"
      title="课程班级"
      width="60%">
      <el-table :data="classsListByCourse"
        border
        stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="班级ID"
          prop="classsId"></el-table-column>
        <el-table-column label="班级名称"
          prop="classsName"></el-table-column>
        <el-table-column label="所属专业"
          prop="majorName"></el-table-column>
        <el-table-column label="所属学院"
          prop="departmentName"></el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="viewClasssDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 自定义删除动画样式 */
.deleting-row {
  animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateX(0);
  }

  to {
    opacity: 0;
    transform: translateX(20px);
  }
}

/* 课程简介样式 */
.course-info {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>

<script>
import {
  getCourseList,
  addCourse,
  updateCourse,
  deleteCourse,
  getCourseDetail,
  getClasssByCourseId
} from '@/api/course';

export default {
  data() {
    return {
      // 查询参数
      queryInfo: {
        pagenum: 1,       // 当前页码
        pagesize: 10,     // 每页显示数量
        query: '',        // 查询关键词
        orderBy: 0        // 排序方式(后端默认0)
      },
      // 课程列表数据
      courseList: [],
      // 总数据条数
      total: 0,
      // 控制对话框显示与隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      viewClasssDialogVisible: false,
      // 正在删除的ID列表（用于动画）
      deletingIds: [],
      // 班级列表（用于查看课程班级）
      classsListByCourse: [],
      // 添加课程表单数据
      addForm: {
        courseId: "",
        courseName: "",
        courseInfo: "",
        teacherId: ""
      },
      // 添加表单验证规则
      addFormRules: {
        courseId: [{ required: true, message: "请输入课程ID", trigger: "blur" }],
        courseName: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        courseInfo: [{ required: true, message: "请输入课程简介", trigger: "blur" }],
        teacherId: [{ required: true, message: "请输入授课教师ID", trigger: "blur" }]
      },
      // 编辑课程表单数据
      editForm: {
        courseId: "",
        courseName: "",
        courseInfo: "",
        teacherId: ""
      },
      // 编辑表单验证规则
      editFormRules: {
        courseName: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        courseInfo: [{ required: true, message: "请输入课程简介", trigger: "blur" }],
        teacherId: [{ required: true, message: "请输入授课教师ID", trigger: "blur" }]
      }
    };
  },
  created() {
    // 初始化数据
    this.fetchCourseList();
  },
  methods: {
    // 获取课程列表
    async fetchCourseList() {
      try {
        // 构建请求体参数
        const requestBody = {
          courseName: this.queryInfo.query
        };

        const res = await getCourseList(
          this.queryInfo.pagenum,
          this.queryInfo.pagesize,
          this.queryInfo.orderBy,
          requestBody
        );

        if (res.code === 200) {
          this.courseList = res.data.list || [];
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || '获取课程列表失败');
        }
      } catch (error) {
        console.error('获取课程列表失败:', error);
        this.$message.error('获取课程列表失败，请稍后再试');
      }
    },

    // 处理搜索
    handleSearch() {
      this.queryInfo.pagenum = 1; // 重置页码
      this.fetchCourseList();
    },

    // 显示编辑对话框
    async showEditDialog(courseId) {
      try {
        // 获取课程详情
        const res = await getCourseDetail(courseId);
        if (res.code === 200) {
          this.editForm = res.data;
          this.editDialogVisible = true;
        } else {
          this.$message.error(res.message || '获取课程详情失败');
        }
      } catch (error) {
        console.error('获取课程详情失败:', error);
        this.$message.error('获取课程详情失败，请稍后再试');
      }
    },

    // 查看课程关联的班级
    async viewClasssByCourse(courseId) {
      try {
        const res = await getClasssByCourseId(courseId);
        if (res.code === 200) {
          this.classsListByCourse = res.data.list || [];
          this.viewClasssDialogVisible = true;
        } else {
          this.$message.error(res.message || '获取课程班级失败');
        }
      } catch (error) {
        console.error('获取课程班级失败:', error);
        this.$message.error('获取课程班级失败，请稍后再试');
      }
    },

    // 提交添加表单
    async submitAddForm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await addCourse(this.addForm);
            if (res.code === 200) {
              this.$message.success('添加课程成功');
              this.addDialogVisible = false;
              this.fetchCourseList();
              // 重置表单
              this.$nextTick(() => {
                this.$refs.addFormRef.resetFields();
              });
            } else {
              this.$message.error(res.message || '添加课程失败');
            }
          } catch (error) {
            console.error('添加课程失败:', error);
            this.$message.error('添加课程失败，请稍后再试');
          }
        }
      });
    },

    // 提交编辑表单
    async submitEditForm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateCourse(this.editForm);
            if (res.code === 200) {
              this.$message.success('修改课程成功');
              this.editDialogVisible = false;
              this.fetchCourseList();
            } else {
              this.$message.error(res.message || '修改课程失败');
            }
          } catch (error) {
            console.error('修改课程失败:', error);
            this.$message.error('修改课程失败，请稍后再试');
          }
        }
      });
    },

    // 处理删除
    async handleDelete(courseId) {
      try {
        // 添加删除动画标记
        this.deletingIds.push(courseId);

        // 确认删除
        await this.$confirm(
          '确认删除该课程? 此操作不可恢复',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 调用删除API
        const res = await deleteCourse(courseId);
        if (res.code === 200) {
          this.$message.success('删除课程成功');
          this.fetchCourseList();
        } else {
          this.$message.error(res.message || '删除课程失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除课程失败:', error);
          this.$message.error('删除课程失败，请稍后再试');
        }
      } finally {
        // 移除动画标记
        this.deletingIds = this.deletingIds.filter(id => id !== courseId);
      }
    },

    // 获取删除行样式
    getRowClass({ row }) {
      return this.deletingIds.includes(row.courseId) ? 'deleting-row' : '';
    },

    // 处理分页大小变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.fetchCourseList();
    },

    // 处理页码变化
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.fetchCourseList();
    }
  }
};
</script>
